import { Toast } from "vant";
import axios from "axios";
import qs from "qs";
import CONFIG from "@/config";
import Indicator from "@/components/Indicator/index";

let needLoadingRequestCount = 0;
//那么 showFullScreenLoading() tryHideFullScreenLoading() 要干的事儿就是将同一时刻的请求合并。
//声明一个变量 needLoadingRequestCount，每次调用showFullScreenLoading方法 needLoadingRequestCount + 1。
//调用tryHideFullScreenLoading()方法，needLoadingRequestCount - 1。needLoadingRequestCount为 0 时，结束 loading。

function startLoading() {
  Indicator.open();
  // toastLoading.show();
}

function endLoading() {
  Indicator.close();
  // toastLoading.hide();
}

function showFullScreenLoading() {
  if (needLoadingRequestCount === 0) {
    startLoading();
  }
  needLoadingRequestCount++;
}

function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return;
  needLoadingRequestCount--;
  if (needLoadingRequestCount === 0) {
    endLoading();
  }
}

const CancelToken = axios.CancelToken;
let requestMap = new Map();
let prevTime = new Date().getTime();

export default function fetch(options) {
  options.data = options.data ? options.data : {};
  // 100ms以内的重复请求都会被清空
  let nowTime = new Date().getTime();
  if (nowTime - prevTime >= 100) {
    requestMap = new Map();
  }
  // 赋值下一次请求的时间
  prevTime = nowTime;

  return new Promise((resolve, reject) => {
    if (!options.hideLoading) {
      showFullScreenLoading();
    }
    const instance = axios.create({
      baseURL: CONFIG.request.BASE_URL,
      headers: {
        Accept: "application/json",
        "Content-type": "application/json",
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Credentials": true
      },
      validateStatus: function(status) {
        // return status >= 200 && status <= 500 // default 国外标准restful需要
        return status === 200;
      },
      // `timeout` specifies the number of milliseconds before the request times out.
      // If the request takes longer than `timeout`, the request will be aborted.
      timeout: CONFIG.request.timeout, // default is `0` (no timeout)

      // `withCredentials` indicates whether or not cross-site Access-Control requests
      // should be made using credentials
      withCredentials: false // default
    });
    instance.interceptors.request.use(
      config => {
        // 防重复提交(100ms以内我们防止相同的请求提交)
        const keyString = qs.stringify(
          Object.assign({}, { url: config.url, data: config.data })
        );
        if (requestMap.get(keyString)) {
          // 取消当前请求
          config.cancelToken = new CancelToken(cancel => {
            console.log("关闭的请求", keyString);
            cancel("Please slow down a little");
          });
        }
        requestMap.set(keyString, true);
        Object.assign(config, { _keyString: keyString });
        return config;
      },
      error => {
        return Promise.reject(error);
      }
    );

    instance.interceptors.response.use(
      response => {
        return response;
      },
      error => {
        return Promise.reject(error);
      }
    );

    // 请求处理
    instance(options)
      .then(res => {
        if (res.status === 200) {
          if (res.data.retCode === "2") {
            //登录出错
            if (res.data.retInfo) {
              Toast.fail(res.data.retInfo);
            }
          } else if (res.data.retCode === "3") {
            //服务器错误
            Toast.fail('服务器错误');
          }
          resolve(res.data);
        } else {
          resolve(res.data);
        }
        tryHideFullScreenLoading();
        return false;
      })
      .catch(error => {
        console.error(`来自响应结果的错误:${error}`);
        Toast.fail('网络异常，请稍候再试');
        setTimeout(() => {
          tryHideFullScreenLoading();
        }, 2000);
        reject(error);
      });
  });
}
